package com.ocom.mqsimple.business.account;

import com.alibaba.fastjson.JSON;
import com.ocom.common.resp.Result;
import com.ocom.mqsimple.config.AddAccountMqConfig;
import com.ocom.mqsimple.feign.PayConfigClientService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;


@Component
public class AccountConsumerMqListener {

	private Logger logger = LoggerFactory.getLogger(AccountConsumerMqListener.class);


	@Autowired
	private PayConfigClientService payConfigClientService;

	/**
	 * 把该监听命名为A监听
	 * 监听队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues = AddAccountMqConfig.ADDACCOUNT_QUEUE)
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		logger.info("addaccount_queue 消费中");
		logger.info("message【{}】",message);
		String addXFAccount = new String(message.getBody(), StandardCharsets.UTF_8);


	//TODO 数据库操作样例
		logger.info("addXFAccount-start:【{}】",addXFAccount);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());

		try {

			Map map = JSON.parseObject(addXFAccount, Map.class);
			logger.info("消费数据【{}】",map);
			map.put("accTypeId",map.get("accountId"));
			Result result = payConfigClientService.AddXFAccount(map);
			logger.info("消费-添加消费账户【{}】",result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("消息处理失败:【{}】",addXFAccount);
			logger.info("出现异常后，原本队列消息进入死信队列");

		}


		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		logger.info("addXFAccount-end:【{}】",addXFAccount);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());
	}

	/**
	 * 把该监听命名为B监听
	 * 监听死信队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues =  AddAccountMqConfig.ADDACCOUNT_DIE_QUEUE)
	public void processForDie(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		//死信队列放弃
		channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
	}

}
